package cn.xiangxu.login.contoller;

import java.io.Serializable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.xiangxu.login.entity.Admin;
import cn.xiangxu.login.service.LoginService;
import cn.xiangxu.login.service.YongHuCaoZuoException;

@Controller("loginController")
public class LoginController implements Serializable {
	
	@Resource(name="loginService")
	private LoginService ls;
	
	@RequestMapping("/toLogin.do")
	public String toLogin() {
		System.out.println("toLogin() : 去往登录页面中...");
		return "jsp/login";
	}
	
	@RequestMapping("/toIndex.do")
	public String toIndex(HttpServletRequest request, HttpSession session) {
		System.out.println("toIndex() : 用户信息正确就转发到主页面");
//		读取请求参数
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String password2 = request.getParameter("password2");
//		打印读取到的请求参数
		System.out.println("name : " + name);
		System.out.println("password : " + password);
		System.out.println("password2 : " + password2);
//		判断两次密码是否一致：不一致就抛出应用异常
		if(!password.equals(password2)) {
			System.out.println("两次密码不一致");
			throw new YongHuCaoZuoException("两次输入的密码不一致");
		}
		
		Admin admin = ls.serviceLogin(name, password);
		session.setAttribute("admin", admin);
		
		return "redirect:index.do"; 
	}
	
	@RequestMapping("/index.do")
	public String index() {
		System.out.println("index() : 去往主页面中...");
		return "jsp/index";
	}
	
//	利用spring框架实现异常处理
	@ExceptionHandler
	public String exceptionHandler(Exception e, HttpServletRequest request) {
		if(e instanceof YongHuCaoZuoException) {
//			应用异常：根据相应的错误信息给用户相关提示信息
			request.setAttribute("failed", e.getMessage());
			return "jsp/login";
		}
		return "jsp/error";
	}
	
}
